const { ServerConfig } = require("../libs/config");
const auth = require("../libs/auth");
const _ = require("lodash");

async function koaAuth(ctx, next) {
  const url = ctx.request.url;
  const token = ctx.request.header["b-json-web-token"];
  console.log("token", token);
  let errMsg = "";
  if (_.includes(ServerConfig.whiteListApi, url)) {
    await next();
  } else {
    const isVerifySuccess = await auth.verifyToken(token);
    if (isVerifySuccess) {
      await next();
    } else {
      errMsg = "认证失败!";
      ctx.response.status = 401;
      ctx.response.body = {
        code: 401,
        error: "Unauthorized",
        message: errMsg,
      };
    }
  }
}

module.exports = koaAuth;
